package com.yangjie.autotest.component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;

import javax.inject.Named;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;

import com.yangjie.autotest.dao.AbstractHbnDao;

@Named("databaseComonentDAO")
public class DBComponentDao extends AbstractHbnDao {
	private static final String TABLE_BACKUP_XML = "tableBackup.xml";

	public void execSQL(String sql) {
		getSession().createSQLQuery(sql).executeUpdate();
	}

	public void backupTable(String tableNames, String backupDir, String schema) throws Exception {
		if (tableNames == null) {
			return;
		}
		Connection conn = getConnection();
		DatabaseConnection connection = new DatabaseConnection(conn, schema);
		QueryDataSet dataSet = new QueryDataSet(connection);
		String[] tableArray = tableNames.split(",");
		for (String tableName : tableArray) {
			dataSet.addTable(tableName.trim());
		}
		FlatXmlDataSet.write(dataSet, new FileOutputStream(backupDir + File.separator + TABLE_BACKUP_XML));

	}

	public void restoreTable(String backupDir, String schema) throws Exception {
		DatabaseConnection connection = new DatabaseConnection(getConnection(), schema);
		IDataSet expectedDataSet = new FlatXmlDataSet(new FileInputStream(backupDir + File.separator + TABLE_BACKUP_XML));
		DatabaseOperation.CLEAN_INSERT.execute(connection, expectedDataSet);
	}

	public void initTable(String fileName, String schema) throws Exception{
		DatabaseConnection connection = new DatabaseConnection(getConnection(), schema);
		IDataSet expectedDataSet = new FlatXmlDataSet(new FileInputStream(fileName));
		DatabaseOperation.CLEAN_INSERT.execute(connection, expectedDataSet);
	}
}
